<?php
namespace app\api\validate;

use think\Validate;
use think\Request;
use app\lib\exception\ParamEx;

/** 
* Document
*/
class Base extends Validate {
    
    public function goCheck($data=[]){
        if(empty($data)){
            $data = Request::instance()->param();
        }
        $res = $this->batch(true)->check($data);
        if($res){
            return true;
        }else{
            // 抛出异常
            throw new ParamEx($this->getError());
        }

    }
    
    public function listGoCheck($data){

        if (! is_array($data)||empty($data)) {
            throw new ParamEx('参数不能为空');
        }
        
        $i = 0;
        foreach ($data as $v) {
            $i++;
            $res = $this->batch()->check($v);
            if(! $res){
                $msg = $this->getError();
                $msg['row'] = $i;
                throw new ParamEx($msg);
            }
        }
        return true;
    }
    /**
     * 通过验证器的数据
     *
     * @param string $data
     * @return void
     */
    public function passData($data=''){
        $data = empty($data)? Request::instance()->param() : $data;
        $resArr = [];
        foreach ($this->rule as $key => $value) {
            if (array_key_exists($key,$data)) {
                $resArr[$key] = $data[$key];
            }
        }
        return $resArr;
    }

    /* -----------自定义验证规则---------------- */

    public function isNotEmpty($value){
        if(empty(trim($value))) return false;
        else return true;
    }

    /**
     * 验证正整数
     *
     * @param string|int|float $value 待验证的数据
     * @return boolean
     */
    protected function isPosInt($value){
        if (floor($value) == $value && ($value + 0) > 0) {
            return true;
        }else{
            return false;
        }
    }
    /**
     * 验证正整数串（逗号分隔）
     *
     * @param string $value
     * @return boolean
     */
    protected function checkIDs($value){
        $value_arr = explode(',',$value);
        if(empty($value_arr)) return false;
        foreach ($value_arr as $v) {
            if(! $this->isPosInt($v)) return false;
        }
        return true;
    }
}